package com.qlogic.commons.web;

import java.io.File;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.qlogic.commons.kernel.BasicFactory;
import com.qlogic.commons.kernel.Kernel;
import com.qlogic.commons.kernel.KernelException;
import com.qlogic.commons.utils.Strings;

/**
 * Servlet Class
 *
 * @web.servlet              name="KernelStartup"
 *                           display-name="Name for KernelStartup"
 *                           description="Description for KernelStartup"
 * @web.servlet-mapping      url-pattern="/KernelStartup"
 * @web.servlet-init-param   name="A parameter"
 *                           value="A value"
 */
public class KernelStartupServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7800622373294614589L;
	
	private static final String KERNEL_STANDALONE = "com.qlogic.commons.kernel.standalone";
	private static final String KERNEL_VERBOSE    = "com.qlogic.commons.kernel.verbose";
	
	private static final String WEB_PREFIX = "web:";
	
	public KernelStartupServlet() {
		super();
	}

	public void init(ServletConfig config) throws ServletException {
		super.init (config);
		String factoryConfig = config.getInitParameter (BasicFactory.FACTORY_CONFIG);
		File factoryConfigFile = null;
		boolean stadalone = true;
		boolean verbose = false;
		if (factoryConfig != null && !factoryConfig.trim ().equals ("")) {
			if (factoryConfig.startsWith (WEB_PREFIX)) {
				factoryConfigFile = new File ( getServletContext().getRealPath(
						factoryConfig.substring (WEB_PREFIX.length ())) );
			} else {
				factoryConfigFile = new File (factoryConfig);
			}
		}
		String debugBeanAccessors = config.getInitParameter (Strings.DEBUG_BEAN_ACCESSORS);
		if (debugBeanAccessors != null && debugBeanAccessors.trim ().equals ("true")) {
			System.setProperty (Strings.DEBUG_BEAN_ACCESSORS, "true");
		}
		String sStandalone = config.getInitParameter (KERNEL_STANDALONE);
		if (sStandalone != null && sStandalone.trim ().equals ("false")) {
			stadalone = false;
		}
		String sVerbose = config.getInitParameter (KERNEL_VERBOSE);
		if (sVerbose != null && sVerbose.trim ().equals ("true")) {
			verbose = true;
		}
		try {
			Kernel kernel = new Kernel (factoryConfigFile, stadalone);
			kernel.start ();
			if (verbose) {
				System.out.println (Kernel.getRootResource ().print (false));
			}
		} catch (KernelException e) {
			e.printStackTrace ();
			throw new ServletException (e);
		}
	}

	public void destroy() {
		try {
			Kernel.getCurrentInstance().stop ();
		} catch (KernelException e) {
		}
		super.destroy();
	}

}
